<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">生产管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/GetProcesview">工艺流程</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 条件搜索 -->
  <div style="margin-top: 20px; width: 1200px">
    <el-form :inline="true" style="font-size: 15px; width: 3000px">
      <el-form-item label="工艺路线编号">
        <el-input v-model="page.ProcessNo" />
      </el-form-item>
      <el-form-item label="工艺路线名称" style="margin-left: -20px">
        <el-input v-model="page.ProcessName" />
      </el-form-item>
      <el-form-item label="是否启用:" style="margin-left: -20px">
        <el-radio-group v-model="page.isvailable">
          <el-radio label="是" :value="1" />
          <el-radio label="否" :value="0" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getProcess">搜索</el-button>
        <el-button type="primary" @click="empty">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 显示 -->
  <div style="margin-top: 20px">
    <el-button type="primary" size="small" @click="open(null)">新增</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="processNo" label="工艺编号" width="180">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="open(scope.row)">
            {{ scope.row.processNo }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="processName" label="工艺路线名称" width="120" />
      <el-table-column prop="processdescris" label="工艺路线说明" />
      <el-table-column prop="isvailable" label="是否启用">
        <template #default="scope">
          <div style="color: #409eff; font-weight: bold; font-size: 14px">
            {{ scope.row.isvailable == 1 ? "是" : "否" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="processroute" label="备注" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="open(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            size="small"
            @click="delProcess(scope.row.processID)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        v-model:current-page="page.PageIndex"
        v-model:page-size="page.PageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total,sizes, prev, pager, next, jumper"
        :total="page.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- 新增、修改 -->

  <div>
    <el-dialog
      v-model="Eject.dialogFormVisible"
      :title="Eject.title"
      width="1000"
    >
      <el-form :model="form" :inline="true">
        <el-form-item label="编号:" :label-width="Eject.formLabelWidth">
          <el-input
            v-model="form.processNo"
            autocomplete="off"
            style="width: 180px; height: 30px"
            :readonly="form.autoGenerate"
            clearable
            @click.native="handleCodeClick"
          />
          <template slot="prepend">R</template>
          <el-switch
            width="40"
            v-model="form.autoGenerate"
            active-text="自动生成"
            active-color="#67C23A"
            @change="handleSwitchChange"
          />
        </el-form-item>
        <el-form-item label="名称:" :label-width="Eject.formLabelWidth">
          <el-input
            v-model="form.processName"
            placeholder="请输入工艺路线名称"
          />
        </el-form-item>
        <el-form-item label="是否启用:" prop="enable">
          <el-radio-group v-model="form.isvailable">
            <el-radio label="是" :value="true" />
            <el-radio label="否" :value="false" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            v-model="form.processdescris"
            style="width: 900px"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.processroute"
            style="width: 900px"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="saveProcess()">保存</el-button>
          <el-button type="primary" @click="Eject.dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <div>
    <!-- 修改 -->
    <el-dialog
      v-model="Eject.dialogupdataFormVisible"
      :title="Eject.title"
      width="1000"
    >
      <el-form :model="form" :inline="true">
        <el-form-item label="编号:" :label-width="Eject.formLabelWidth">
          <el-input
            v-model="form.processNo"
            autocomplete="off"
            style="width: 180px; height: 30px"
            :readonly="form.autoGenerate"
            clearable
            @click.native="handleCodeClick"
          />
          <template slot="prepend">R</template>
          <el-switch
            width="40"
            v-model="form.autoGenerate"
            active-text="自动生成"
            active-color="#67C23A"
            @change="handleSwitchChange"
          />
        </el-form-item>
        <el-form-item label="名称:" :label-width="Eject.formLabelWidth">
          <el-input
            v-model="form.processName"
            placeholder="请输入工艺路线名称"
          />
        </el-form-item>
        <el-form-item label="是否启用:" prop="enable">
          <el-radio-group v-model="form.isvailable">
            <el-radio label="是" :value="true" />
            <el-radio label="否" :value="false" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            v-model="form.processdescris"
            style="width: 900px"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.processroute"
            style="width: 900px"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="saveupdataProcess()">保存</el-button>
          <el-button type="primary" @click="Eject.dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </template>
      <div>
        <div>
          <el-form-item>
            <el-form-item label="工序编码" prop="warehouseCode">
              <el-input v-model="pages.ProcessCode" />
            </el-form-item>
            <el-form-item label="工序名称" prop="warehouseName">
              <el-input v-model="pages.ProcessName" />
            </el-form-item>
            <el-form-item label="是否启用" prop="isEnabled">
              <el-radio-group v-model="pages.IsEnabled">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-button type="primary" @click="fetchData()">搜索</el-button>
            <el-button type="primary" @click="clearForm()">清空</el-button>
          </el-form-item>
        </div>
        <div>
          <el-button type="primary" @click="openAddDialog">添加</el-button>
          <el-table :data="tableDatas" style="width: 100%">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="processCode" label="工序编码" width="180">
              <template #default="{ row }">
                <span style="color: #409eff; cursor: pointer">{{
                  row.processCode
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="processName" label="工序名称" width="180" />
            <el-table-column prop="isEnabled" label="是否启用" width="120">
              <template #default="{ row }">
                <el-tag v-if="row.isEnabled">是</el-tag>
                <el-tag type="danger" v-else>否</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" width="180" />
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default="scope">
                <el-link
                  type="primary"
                  size="small"
                  @click="openEditDialog(scope.row)"
                  >修改</el-link
                >
                <!-- <el-link type="primary" size="small" @click="handleDelete(scope.row.processInfoId)">删除</el-link> -->
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加对话框 -->
          <el-dialog
            v-model="addDialogVisible"
            title="添加工序设置"
            width="800"
          >
            <el-form :model="addForm" style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-form-item label="工序编码" prop="processCode">
                  <div style="display: flex; align-items: center; gap: 10px">
                    <el-input
                      v-model="addForm.processCode"
                      placeholder="请输入工序编码"
                    />
                    <el-switch
                      v-model="addForm.autoGenerate"
                      size="small"
                      @change="handleAutoGenerate"
                      label="自动生成"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="工序名称" prop="processName">
                  <el-input
                    v-model="addForm.processName"
                    placeholder="请输入工序名称"
                  />
                </el-form-item>
                <!-- 隐藏外键输入框 -->
                <el-form-item
                  label="外键"
                  prop="operationStepInfoId"
                  style="display: none"
                >
                  <el-input
                    v-model="addForm.operationStepInfoId"
                    placeholder="请输入工序名称"
                  />
                </el-form-item>
                <el-form-item label="是否启用" prop="isEnabled" required>
                  <el-radio-group v-model="addForm.isEnabled">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="工序说明" prop="processDescription">
                  <el-input
                    v-model="addForm.processDescription"
                    placeholder="请输入内容"
                    type="textarea"
                    rows="2"
                  />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                  <el-input
                    v-model="addForm.remarks"
                    placeholder="请输入内容"
                    type="textarea"
                    rows="2"
                  />
                </el-form-item>
              </div>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm"
                  >确定</el-button
                >
              </div>
            </template>
          </el-dialog>

          <!-- 修改对话框 -->
          <el-dialog v-model="editDialogVisible" title="修改工序" width="500">
            <el-form :model="editForm">
              <el-form-item label="工序ID" prop="processInfoId">
                <el-input v-model="editForm.processInfoId" disabled />
              </el-form-item>
              <el-form-item label="工序编码" prop="processCode">
                <el-input v-model="editForm.processCode" />
              </el-form-item>
              <el-form-item label="工序名称" prop="processName">
                <el-input v-model="editForm.processName" />
              </el-form-item>
              <!-- 隐藏外键输入框 -->
              <el-form-item
                label="外键"
                prop="operationStepInfoId"
                style="display: none"
              >
                <el-input v-model="editForm.operationStepInfoId" />
              </el-form-item>
              <el-form-item label="是否启用" prop="isEnabled" required>
                <el-radio-group v-model="editForm.isEnabled">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="editForm.remarks" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEditForm"
                  >提交</el-button
                >
              </div>
            </template>
          </el-dialog>
        </div>

        <!-- <div class="demonstration"1111111sssww></div> -->
        <el-pagination
          v-model:current-page="pages.Index"
          v-model:page-size="pages.Size"
          :page-sizes="[1, 5, 10, 15]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pages.TotalCount"
          @size-change="handleSizeChanges"
          @current-change="handleCurrentChanges"
          prev-text="上一页"
          next-text="下一页"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

import axios from "axios";

const apiUrl = import.meta.env.VITE_API_URL;
console.log(import.meta.env); // 打印环境变量
const tableData = ref([]);
onMounted(() => {
  getProcess(); //获取工艺流程
  // generateCode(); //生成工艺编号
});

const page = reactive({
  PageIndex: 1,
  PageSize: 10,
  totalCount: 0,
  totalPage: 0,
  ProcessNo: "",
  ProcessName: "",
  isvailable: null,
});
const Eject = reactive({
  dialogFormVisible: false,
  dialogupdataFormVisible: false,
  formLabelWidth: "100px",
  title: "",
  Isture: true,
});
// 获取工艺流程
const getProcess = () => {
  axios.get(apiUrl+"/T5/Process/GetProcess", { params: page }).then((res) => {
    console.log(res.data.data);
    tableData.value = res.data.data;
    page.totalCount = res.data.totalCount;
    page.totalPage = res.data.totalPage;
  });
};
// 清空
const empty = () => {
  page.ProcessNo = "";
  page.ProcessName = "";
  page.isvailable = null;
  getProcess();
};
// 新增
const form = reactive({
  processID: 0,
  processNo: "",
  processName: "",
  processdescris: "",
  processroute: "",
  isvailable: false,
  isDel: false,
  autoGenerate: false, // 是否自动生成
  workOrderId: 0,
  requisitionid: 0,
  processInfoId: 0,
  noticeId: 0,
});

// 添加工艺流程
const saveProcess = () => {
  if (Eject.Isture) {
    axios.post(apiUrl+"/T6/Process/CreateProcess", form).then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        form.processNo = "";
        form.autoGenerate = true;
        Eject.dialogFormVisible = false;
        getProcess();
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else {
    /* axios
      .put("http://localhost:5057/api/Process/UpdataProcess", form)
      .then((res) => {
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg);
          Eject.dialogFormVisible = false;
          getProcess();
          return;
        } else {
          ElMessage.error(res.data.msg);
        }
      }); */
  }
};

//修改工艺流程
const saveupdataProcess = () => {
  Eject.dialogupdataFormVisible = true;
  fetchData();
  axios.put(apiUrl+"/T6/Process/UpdataProcess", form).then((res) => {
    if (res.data.code == 206) {
      ElMessage.success(res.data.msg);
      Eject.dialogupdataFormVisible = false;
      getProcess();
      return;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//打开对话框
const open = (row: any) => {
  if (row == null) {
    Eject.dialogFormVisible = true;
    Eject.title = "新增工艺流程";
    Eject.Isture = true;
    (form.processID = 0),
      (form.processNo = ""),
      (form.processName = ""),
      (form.processdescris = ""),
      (form.processroute = ""),
      (form.isvailable = false),
      (form.isDel = false),
      (form.autoGenerate = false);
  } else {
    Eject.dialogupdataFormVisible = true;
    /*  alert(1); */
    Eject.title = "修改工艺流程";

    // Eject.Isture = false;
    (form.processID = row.processID),
      (form.processNo = row.processNo),
      (form.processName = row.processName),
      (form.processdescris = row.processdescris),
      (form.processroute = row.processroute),
      (form.isvailable = row.isvailable),
      (form.isDel = row.isDel),
      (form.autoGenerate = row.autoGenerate);
  }
};

// 生成工艺编号（GYLX+时间戳）
const generateCode = () => {
  const timestamp = new Date()
    .toISOString()
    .replace(/[-:TZ]/g, "")
    .substring(0, 14); // 获取精确到毫秒的时间戳
  form.processNo = `GYLX${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
  form.autoGenerate = val;
  if (val) {
    generateCode(); // 开启自动生成时立即生成
  } else {
    form.processNo = ""; // 关闭时清空编号
  }
};

const handleCodeClick = () => {
  if (form.autoGenerate) {
    generateCode(); // 点击输入框时重新生成
  }
};
// 删除
const delProcess = (processID: any) => {
  // alert(processID);
  axios
    .put(apiUrl+"/T6/Process/DelProcess", {
      processID: processID,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success(res.data.msg);
        getProcess();
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  page.PageSize = val;
  getProcess();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.PageIndex = val;
  getProcess();
};

//#region 工序
/* const size = ref<ComponentSize>('default'); */

const handleSizeChanges = (val: number) => {
  console.log(`${val} items per page`);
  pages.TotalCount = val;
  fetchData();
};
const handleCurrentChanges = (val: number) => {
  console.log(`current page: ${val}`);
  pages.PageCount = val;
  fetchData();
};

const clearForm = () => {
  pages.ProcessCode = "";
  pages.ProcessName = "";
  pages.IsEnabled = true;
  fetchData(); // 可选：清空后自动搜索
};

const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
// 分页数据
const pages = reactive({
  TotalCount: 0,
  PageCount: 0,
  Index: 1,
  Size: 15,
  ProcessCode: "",
  ProcessName: "",
  IsEnabled: true,
});

const addForm = reactive({
  processInfoId: 0,
  processCode: "",
  processName: "",
  isEnabled: true,
  processDescription: "",
  remarks: "",
  operationStepInfoId: null,
  isDelete: true,
  autoGenerate: false,
});

const editForm = reactive({
  processInfoId: 0,
  processCode: "",
  processName: "",
  isEnabled: true,
  processDescription: "",
  remarks: "",
  operationStepInfoId: null,
  isDelete: true,
});

const tableDatas = ref([]);

// 获取数据（修改后）
const fetchData = () => {
  axios
    .get(apiUrl+"/T5/Setting/ProcessingoShow", {
      params: pages,
    })
    .then((res) => {
      tableDatas.value = res.data.data;
      pages.TotalCount = res.data.totalCount;
      pages.PageCount = res.data.pageCount;
    });
};

// 打开添加对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
  Object.assign(addForm, {
    processInfoId: 0,
    processCode: "",
    processName: "",
    processDescription: "",
    isEnabled: true,
    remarks: "",
    operationStepInfoId: null,
    isDelete: true,
    autoGenerate: false,
  });
};

// 提交添加表单
const submitAddForm = async () => {
  // 自动生成时间格式编码
  if (addForm.autoGenerate) {
    const now = new Date();
    addForm.processCode = now
      .toISOString()
      .replace(/[-:.T]/g, "")
      .substring(0, 14); // 取年月日时分（14位）
  }

  // 五位长度验证（这里因时间格式是14位，实际需求若需固定长度可调整，当前按时间格式处理）
  if (!addForm.processCode) {
    ElMessage.error("工序编码不能为空");
    return;
  }

  // 检查必填项
  if (!addForm.processCode || !addForm.processName) {
    ElMessage.error("工序编码和工序名称为必填项");
    return;
  }

  const addData = {
    processInfoId: addForm.processInfoId,
    processCode: addForm.processCode,
    processName: addForm.processName,
    isEnabled: addForm.isEnabled,
    processDescription: addForm.processDescription,
    remarks: addForm.remarks,
    operationStepInfoId: addForm.processInfoId,
    isDelete: addForm.isDelete,
  };

  axios
    .post(apiUrl+"/T6/api/setting/Processinfo", addData)
    .then((res) => {
      if (res.data.code === 100) {
        ElMessage.success("添加成功");
        addDialogVisible.value = false;
        fetchData();
      } else {
        ElMessage.error("添加失败");
      }
    })
    .catch((error) => {
      if (error.response && error.response.status === 400) {
        ElMessage.error("添加请求参数错误，请检查表单数据");
        console.log("错误请求数据:", addData);
      } else {
        ElMessage.error("添加请求出错，请检查网络或服务器状态");
      }
      console.error(error);
    });
};

// 打开修改对话框并反填数据
const openEditDialog = (row: any) => {
  editDialogVisible.value = true;
  Object.assign(editForm, row);
};

// 提交修改表单
const submitEditForm = async () => {
  // 检查必填项
  if (!editForm.processCode || !editForm.processName) {
    ElMessage.error("工序编码和工序名称为必填项");
    return;
  }

  const editData = {
    processInfoId: editForm.processInfoId,
    processCode: editForm.processCode,
    processName: editForm.processName,
    isEnabled: editForm.isEnabled,
    processDescription: editForm.processDescription,
    remarks: editForm.remarks,
    operationStepInfoId: editForm.processInfoId,
    isDelete: editForm.isDelete,
  };

  axios
    .put(apiUrl+"/T6/setting/UpdateProcessinfo", editData)
    .then((res) => {
      if (res.data.code === 206) {
        ElMessage.success("修改成功");
        editDialogVisible.value = false;
        fetchData();
      } else {
        ElMessage.error("修改失败");
      }
    })
    .catch((error) => {
      if (error.response && error.response.status === 400) {
        ElMessage.error("修改请求参数错误，请检查表单数据");
        console.log("错误请求数据:", editData);
      } else {
        ElMessage.error("修改请求出错，请检查网络或服务器状态");
      }
      console.error(error);
    });
};

// 自动生成工序编码
const handleAutoGenerate = () => {
  if (addForm.autoGenerate) {
    const now = new Date();
    addForm.processCode = now
      .toISOString()
      .replace(/[-:.T]/g, "")
      .substring(0, 14); // 生成年月日时分（14位）
  } else {
    addForm.processCode = "";
  }
};

// onMounted(() => {
//   fetchData();
// });

//#endregion
</script>

<style scoped>
.el-dialog-width {
  width: 800px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.form-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 60vh;
}

/* .form-box {
  max-width: 1000px;

  height: 300px;
  margin: 0 auto;
  padding: 10px;
}

.form-title {
  color: #303133;
  text-align: center;
  margin-bottom: 30px;
}

.code-container {
  display: flex;
  gap: 15px;
  align-items: center;
}

::v-deep .el-input-group__prepend {
  background-color: #f5f7fa;
  color: #606266;
  border-right: 0;
}

.button-group {
  width: 100%;
  text-align: right;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea ::v-deep .el-textarea__inner {
  resize: vertical;
} */
</style>